<template>
<div style="height: 100%;">
        <baseHeader :clickName.sync="indexName"></baseHeader>

        <section class="content" v-loading="loading.status" :element-loading-text="loading.txt">
            <div :class="is_search ? 'email-query' : 'email-result'">
                <section class="search" v-if="is_search">
                    <div><img alt="邮件搜索" src="./trash.vue/../../../../assets/email/images/search-mail.png" /></div>
                    <el-form :model="search_form" ref="search_form" label-width="148px" class="search-form">
                        <el-form-item label="选择邮件：">
                            <el-select v-model="search_form.mail_name" placeholder="请选择邮件" @change="changeName">
                                <el-option v-for="(item, index) in mailList" :key="index" :label="item.name" :value="item.value"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="邮件状态：">
                            <el-select v-model="search_form.mail_status" placeholder="请选择邮件状态">
                                <el-option v-for="(item, index) in statusList" :key="index" :label="item.name" :value="item.value"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="日期：">
                            <el-col :span="11">
                                <el-form-item>
                                    <el-date-picker 
                                        :picker-options="startPickerOptions"
                                        type="date" 
                                        placeholder="选择开始日期" 
                                        v-model="search_form.start_time"
                                        value-format="yyyy-MM-dd"
                                        style="width: 100%;">
                                    </el-date-picker>
                                </el-form-item>
                            </el-col>
                            <el-col :span="2" style="text-align: center;">-</el-col>
                            <el-col :span="11">
                                <el-form-item>
                                    <el-date-picker 
                                        :picker-options="endPickerOptions"
                                        type="date" 
                                        placeholder="选择结束日期" 
                                        v-model="search_form.end_time" 
                                        value-format="yyyy-MM-dd"
                                        style="width: 100%;">
                                    </el-date-picker>
                                </el-form-item>
                            </el-col>
                        </el-form-item>
                        <el-form-item label="发件人：">
                            <el-input v-model="search_form.recipient" clearable></el-input>
                        </el-form-item>
                        <el-form-item label="邮件主题包含文字：">
                            <el-input v-model="search_form.subject" clearable></el-input>
                        </el-form-item>
                        <el-form-item label="邮件内容：">
                            <el-input v-model="search_form.content" clearable></el-input>
                        </el-form-item>
                        <el-form-item label="附件文件名：">
                            <el-input v-model="search_form.accessory" clearable></el-input>
                        </el-form-item>
                        <div class="query-btn"><el-button type="primary" @click="getMailList('search_form')">查询</el-button></div>
                    </el-form>
                </section>

                <section v-else>
                    <div class="back-query" @click="resetQuery"><i class="el-icon-arrow-left"></i>查询结果</div>
                    <el-table
                        :data="listData"
                        border
                        max-height="600"
                        style="width: 100%">
                        <el-table-column
                            label="序号"
                            type="index"
                            align="center"
                            width="60">
                        </el-table-column>
                        <el-table-column
                            prop="subject"
                            label="主题"
                            align="center"
                            show-overflow-tooltip>
                            <template slot-scope="scope">
                                <span class="mail-detail" @click="toDeatils(scope.row.id, scope.row.flag)">{{scope.row.subject}}</span>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="flag"
                            label="模块"
                            align="center"
                            show-overflow-tooltip>
                            <template slot-scope="scope">
                                {{mailList[scope.row.flag - 1].name}}
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="user_name"
                            label="发送人"
                            align="center"
                            show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column
                            prop="receiver"
                            label="接收人"
                            align="center"
                            show-overflow-tooltip>
                            <template slot-scope="scope">
                                <span>{{getUserName(scope.row.user)}}</span>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="create_time"
                            label="发送日期"
                            align="center"
                            show-overflow-tooltip>
                        </el-table-column>
                        <el-table-column
                            prop="adjunct"
                            label="附件"
                            align="center"
                            show-overflow-tooltip >
                            <template slot-scope="scope">
                                <span>{{getFileName(scope.row.file)}}</span>
                            </template>
                        </el-table-column>
                        <el-table-column
                            prop="status"
                            label="状态"
                            align="center"
                            show-overflow-tooltip>
                            <template slot-scope="scope">
                                <span v-if="scope.row.flag == 1">
                                    <img v-if="getMailStatus(scope.row.user)" src="./../../../assets/email/images/have-read.png" />
                                    <img v-else src="./../../../assets/email/images/unread.png" />
                                </span>
                                <span v-else>-</span>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div class="table-pagination" v-show="total_number > 10">
                        <el-pagination
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                            :current-page="result_param.page_index"
                            :page-sizes="[10, 20, 30, 40, 50, 100]"
                            :page-size="result_param.page_size"
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="total_number">
                        </el-pagination>
                    </div>
                </section>
            </div>
        </section>
    </div>
    
</template>

<script>
    import baseHeader from './basse-header';

    export default {
        data() {
            return {
                indexName: 'query',
                is_search: true,
                total_number: 0, // 查询数据总数
                startPickerOptions: this.beginDate(),
                endPickerOptions: this.endDate(),
                mailList: [
                    {
                        name: '收件箱',
                        value: '1'
                    },
                    {
                        name: '草稿箱',
                        value: '2'
                    },
                    {
                        name: '已发送',
                        value: '3'
                    },
                    {
                        name: '废纸篓',
                        value: '4'
                    }
                ],
                statusList: [
                    {
                        name: '所有',
                        value: '0' // 传参为空
                    },
                    {
                        name: '已读',
                        value: '1'
                    },
                    {
                        name: '未读',
                        value: '2'
                    }
                ],
                listData: [],
                loading:{
					status:false,
					txt:'获取数据...',
				},
                result_param: {
                    page_index: 1,
                    page_size: 10
                },
                search_form: {
                    mail_name: '1',
                    mail_status: '0',
                    start_time: '',
                    end_time: '',
                    recipient: '',
                    subject: '',
                    content: '',
                    accessory: ''
                },
            }
        },
        created() {
            if (deep_clone(this.$store.getters.query_search)) {
                let query_search = deep_clone(this.$store.getters.query_search);

                this.is_search = false;
                this.search_form.mail_name = query_search.flag;
                this.search_form.start_time = query_search.start_time;
                this.search_form.end_time = query_search.end_time;
                this.search_form.subject = query_search.subject;
                this.search_form.content = query_search.content;
                this.search_form.recipient = query_search.user_name;
                this.search_form.accessory = query_search.file;
                this.search_form.mail_status = query_search.status ? query_search.status : '0';
                this.result_param.page_index = query_search.page_index;
                this.result_param.page_size = query_search.page_size;
                
                this.getMailList();
            }
        },
        components: {
            baseHeader
        },
        methods: {
            /**
             * 返回查询页
             */
            resetQuery() {
                this.is_search = true;
                this.is_search = 'email-query';
            },
            /**
             * 
             */
            changeName(val) {
                if (val == 1) {
                    this.statusList = [
                        {
                            name: '所有',
                            value: '0'
                        },
                        {
                            name: '已读',
                            value: '1'
                        },
                        {
                            name: '未读',
                            value: '2'
                        }
                    ]
                } else {
                    this.statusList = [
                        {
                            name: '所有',
                            value: '0'
                        }
                    ]
                    this.search_form.mail_status = '0';
                }
            },
            /**
             * 获取邮件是否已读
             * @param {Object} 收件人列表
             */
            getMailStatus(obj) {
                let flag = false;

                obj.forEach(item => {
                    if (item.receiver == this.$g.user_id && item.is_read == 1) {
                        flag = true;
                    }
                })

                return flag;
            },
            /**
             * 获取附件名称
             * @param {Object} obj 附件列表
             */
            getFileName(obj) {
                if (is_empty(obj)) {
                    return '';
                } else {
                    let text = '';

                    obj.forEach((item, index) => {
                        text += (index != 0 ? '，' : '') + item.name + '.' + item.postfix;
                    })

                    return text;
                }
            },
            /**
             * 获取收件人名称
             * @param {Object} obj 收件人列表
             */
            getUserName(obj) {
                if (is_empty(obj)) {
                    return '';
                } else {
                    let text = '';

                    obj.forEach((item, index) => {
                        text += (index != 0 ? '，' : '') + item.name;
                    })

                    if (text === '') {
                        text = '无';
                    }

                    return text;
                }
            },
            /**
             * 开始时间必须小于结束时间
             */
            beginDate() {
                let self = this;

                return {
                    disabledDate(time) {
                        if (self.search_form.end_time) {
                            return new Date(self.search_form.end_time).getTime() < time.getTime() || time.getTime() > Date.now();
                        } else {
                            return time.getTime() > Date.now(); // 开始时间不选时，结束时间最大值小于等于当天
                        }
                    }
                }
            },
            /**
             * 结束时间必须大于开始时间
             */
            endDate() {
                let self = this;

                return {
                    disabledDate(time) {
                        if(self.search_form.start_time) {
                            return (new Date(self.search_form.start_time).getTime() - 24*60*60*1000) > time.getTime() || time.getTime() > Date.now();
                        } else {
                            return time.getTime() > Date.now(); //开 始时间不选时，结束时间最大值小于等于当天
                        }
                    }
                }
            },
            /**
             * 重置页面
             */
            reset() {
                this.is_search = true;
                this.listData = [];
                this.result_param.page_index = 1;
                this.result_param.page_size = 10;
                this.search_form = {
                    mail_name: '1',
                    mail_status: '0',
                    start_time: '',
                    end_time: '',
                    recipient: '',
                    subject: '',
                    content: '',
                    accessory: ''
                }
            },
            /**
             * 路由跳转
             * @param {String} name 具体页面
             */
            linkTo(name) {
                this.$router.push(`/email/${name}`);
            },
            /**
             * 跳转到详细页
             * @param {Stirng} id 邮件 id
             */
            toDeatils(id, flag) {
                this.$router.push(`/email/mail-detail?id=${id}&flag=${flag}`);
            },
            /**
             * 邮件查询
             */
            getMailList() {
                this.loading.status = true;

                let params = {
                    flag: this.search_form.mail_name,
                    start_time: this.search_form.start_time,
                    end_time: this.search_form.end_time,
                    subject: this.search_form.subject,
                    content: this.search_form.content,
                    user_name: this.search_form.recipient,
                    file: this.search_form.accessory,
                    status: this.search_form.mail_status === '0' ? null : this.search_form.mail_status,
                    page_index: this.result_param.page_index,
                    page_size: this.result_param.page_size,
                }
                let success = (res => {
                    this.loading.status = false;
                    
                    if (res.data.data.length > 0) {
                        this.is_search = false;
                        this.listData = res.data.data;
                        this.total_number = res.data.data_sum;
                        this.$store.commit('SET_QUERYSEARCH', params);
                    } else {
                        this.$message.error('暂无数据');
                    }
                });

                this.$ajax({
                    url: "api/email/lists",
                    method: "get",
                    params: params,
                    func: {success: success}
                });
            },
            /**
             * 切换每页显示的数据
             * @param {String} val 每页的数据
             */
            handleSizeChange(val) {
		    	this.result_param.page_index = 1;
		    	this.result_param.page_size = val;
		    	this.getMailList();
            },
            /**
             * 切换页数
             * @param {String} val 页数
             */
		    handleCurrentChange(val) {
		    	this.result_param.page_index = val;
		    	this.getMailList();
		    },
        },
    }
</script>

<style lang="scss">
    .content {
        height: calc(100% - 68px);
    }

    .email-query {
        position: relative;
        margin: 30px auto;
        width: 1000px;
        height: calc(100% - 60px);
        background: #fff;
        overflow: hidden;
        box-sizing: border-box;

        .search {
            padding: 44px 200px 0;
            height: 100%;
            overflow: scroll;
            box-sizing: border-box;

            >div:first-child {
                margin-bottom: 60px;
                text-align: center;
            }

            .el-form .el-form-item .el-select {
                width: 100%;
            }

            .query-btn {
                text-align: center;

                button {
                    width: 100%;
                }
            }
        }
    }

    .email-result {
        padding: 30px;
        width: 100%;
        height: 100%;
        background: #fff;
        overflow: hidden;
        box-sizing: border-box;

        .back-query {
            font-size: 17px;
            display: inline-block;
            width: 100px;
            cursor: pointer;
            padding: 13px 0;

            i {
                margin-right: 4px;
            }
        }

        .mail-detail {
            color: #6178A5;
            cursor: pointer;
        }
    }
</style>